{% extends "base.html" %}
{% block content %}
<h2>Prescriptions</h2>

<section class="card">
  <h3>Create Prescription</h3>
  <form method="post" action="{{ url_for('create_prescription') }}" id="prescription-form">
    <input name="appointment_id" placeholder="Appointment ID" required />
    <input name="prescribed_by" placeholder="Doctor/Staff ID" required />
    <textarea name="notes" placeholder="Notes"></textarea>

    <h4>Items</h4>
    <div id="items-container">
      <div class="item-row">
        <input name="items-0-medication_id" placeholder="Medication ID" required />
        <input name="items-0-dosage" placeholder="Dosage (e.g. 500mg)" />
        <input name="items-0-frequency" placeholder="Frequency (e.g. 2/day)" />
        <input name="items-0-duration_days" placeholder="Duration days" />
        <button type="button" class="remove-item" onclick="removeItem(this)">Remove</button>
      </div>
    </div>
    <button type="button" id="add-item">Add Item</button>
    <br><br>
    <button type="submit">Create Prescription</button>
  </form>
</section>

<section class="card">
  <h3>All Prescriptions</h3>
  <table class="striped">
    <thead><tr><th>ID</th><th>Appointment</th><th>Prescribed By</th><th>Issued At</th><th>Notes</th></tr></thead>
    <tbody>
      {% for p in prescriptions %}
      <tr>
        <td><a href="{{ url_for('view_prescription', prescription_id=p.prescription_id) }}">{{ p.prescription_id }}</a></td>
        <td>{{ p.appointment_id }}</td>
        <td>{{ p.prescribed_by }}</td>
        <td>{{ p.issued_at or "-" }}</td>
        <td>{{ p.notes or "-" }}</td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</section>

<script>
let idx = 1;
document.getElementById('add-item').addEventListener('click', function(){
  const container = document.getElementById('items-container');
  const div = document.createElement('div');
  div.className = 'item-row';
  div.innerHTML = `
    <input name="items-${idx}-medication_id" placeholder="Medication ID" required />
    <input name="items-${idx}-dosage" placeholder="Dosage" />
    <input name="items-${idx}-frequency" placeholder="Frequency" />
    <input name="items-${idx}-duration_days" placeholder="Duration days" />
    <button type="button" class="remove-item" onclick="removeItem(this)">Remove</button>
  `;
  container.appendChild(div);
  idx++;
});
function removeItem(btn){
  btn.parentNode.remove();
}
</script>
{% endblock %}
